import { toast } from './util.js'
import storage  from './storage.js'

let config = {
	apiUrl: 'http://192.168.0.156',
	// apiUrl: 'https://livetest.qiyitong91.com',
}

/**
 * 
 * @param {*} url 
 * @param {*} params 
 * @param {*} methods 
 * @param {*} isFormData 
 */
const request = (url, params, methods, isFormData = true) => {
	return new Promise(async (resolve, reject) => {
		let sendUrl = url.indexOf('https://') > -1 ? url : config.apiUrl + url;
		let token = storage.get('userinfo').token?storage.get('userinfo').token:'YZxpd0lSInYK6gabSE3CitKF';
		// let appName = getApp().globalData.appName;
		uni.request({
			url: sendUrl,
			method: methods || 'POST',
			data: {token:token,...params},
			timeout: 1000*12,
			header: {
				'content-type': isFormData ? 'application/x-www-form-urlencoded' : 'application/json',
				'zrjkAppcode': getApp().globalData.zrjkAppCode 
			},
			success(res) {
				if (res.statusCode == 200) {
					if (res.data.code === 200) {
						resolve(res.data)
					} else {
						toast(res.data.msg)
					}
				} else {
					toast("服务器错误:" + res.statusCode);
				}
			},
			fail(err) {
				toast(err.errMsg)
			}
		})
	})
}
const http = {
	get: (url, data, isFormData) => {
		return request(url, data, 'GET', isFormData)
	},
	post: (url, data, isFormData) => {
		return request(url, data, 'POST', isFormData)
	},
	put: (url, data, isFormData) => {
		return request(url, data, 'PUT', isFormData)
	},
	del: (url, data, isFormData) => {
		return request(url, data, 'DELETE', isFormData)
	},
}
export default http